package com.read.exception;

import com.read.common.R;
import com.read.common.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @date
 * @desc
 */
@ControllerAdvice  // controller 层 出现异常 触发通知
@ResponseBody    // 向前端响应json数据
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 拦截业务异常，返回业务异常信息
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(BusinessErrorException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleBusinessError(BusinessErrorException ex) {
        Integer code = ex.getCode();
        String message = ex.getMessage();
        return R.error().code(code).message(message);
    }

    /**
     * 缺少请求参数异常
     *
     * @param ex MissingServletRequestParameterException
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public R handleHttpMessageNotReadableException(
            MissingServletRequestParameterException ex) {
        log.error("缺少请求参数，{}", ex.getMessage());
        return R.setResult(ResultCodeEnum.MISSING_PARAM);
    }


    /**
     * 空指针异常
     *
     * @param ex NullPointerException
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleTypeMismatchException(NullPointerException ex) {
        log.error("空指针异常，{}", ex.getMessage());
        return R.setResult(ResultCodeEnum.NULL_POINT);
    }

    /**
     * 系统异常 预期以外异常
     *
     * @param ex
     * @return 项目中，我们一般都会比较详细的去拦截一些常见异常，拦截 Exception 虽然可以一劳永逸，
     * 但是不利于我们去排查或者定位问题。实际项目中，可以把拦截 Exception 异常写在 GlobalExceptionHandler
     * 最下面，如果都没有找到，最后再拦截一下 Exception 异常，保证输出信息友好。
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleUnexpectedServer(Exception ex) {
        log.error("系统异常：", ex);
        ex.printStackTrace();
        return R.setResult(ResultCodeEnum.UNKNOW_RESAON);
    }
}
